<template>
  <div class="login">
    <el-form
      class="login-form"
      label-position="top"
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="手机号" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="form.pass"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="login-btn"
          type="primary"
          :loading="isLoginLoading"
          @click="onSubmit"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getToken } from '@/services/system/login'
import { GetUserByToken } from '@/services/system/user'

export default {
  name: 'LoginIndex',
  data() {
    return {
      form: {
        name: 'test',
        pass: 'test',
      },
      rules: {
        name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        pass: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      isLoginLoading: false,
    }
  },

  methods: {
    async onSubmit() {
      try {
        // 1. 表单验证
        await this.$refs.form.validate()

        // 登录按钮 loading
        this.isLoginLoading = true

        // 2. 获取token
        const { data } = await getToken(this.form)

        // 3. 处理请求结果
        //    失败：给出提示
        if (data.success !== true) {
          this.$message.error(data.msg)
        } else {
          // 保存token到localhost
          this.$store.commit('setToken', data.response.token)
          this.$store.commit('setExpire_In', data.response.expires_in)
          this.GetUserInfo(data.response.token)
        }
      } catch (err) {
        console.log('登录失败', err)
      }

      // 结束登录按钮的 loading
      this.isLoginLoading = false
    },
    async GetUserInfo(token) {
      const params = {
        token: token,
      }
      const { data } = await GetUserByToken(params)
      if (data.success === true) {
        // 1. 登录成功，记录登录状态，状态需要能够全局访问（放到 Vuex 容器中）
        this.$store.commit('setUser', data.response)
        // 2. 然后在访问需要登录的页面的时候判断有没有登录状态（路由拦截器）
        //    成功：跳转回原来页面或首页
        this.$router.push(this.$route.query.redirect || '/')

        this.$message.success('登录成功')
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  .login-form {
    width: 300px;
    background: #fff;
    padding: 20px;
    border-radius: 5px;
  }
  .login-btn {
    width: 100%;
  }
}
</style>
